<?php

function make_seed()
{
  list($usec,$sec) = explode('',microtime());
  return (float) $sec + ((float) $usec *100000);
}


//ini_set ("display_errors", "1");
//error_reporting(E_ALL);

ob_start();
session_start();
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password 
$db_name="pmc"; // Database name 
$tbl_name="users"; // Table name

 
$memberType="";


$currentFile = "location:".$_SERVER["PHP_SELF"];

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

//get verify user
$unameresult = 1;
$passresult = 1;


$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
//$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
//read the results
$count = 0;

while($row = mysql_fetch_assoc($result))
{
  $unameresult = strcmp($row['Username'],$myusername);
  $passresult = strcmp($row['Password'], $mypassword);
  $userid = $row['UserId'];
  if (!($unameresult | $passresult)){
  	$count = 1;
	break;
   }
}

if($count==1){
mt_srand(make_seed()); 
$seedval=rand();
// Register $myusername, $mypassword and redirect to file "login_success.php"
//$db_field = mysql_fetch_assoc($result)
$memberType = $row['MemberType'];
session_register("myusername");
session_register("mypassword"); 
session_register("memberType");
$_SESSION['userid'] = $userid;
$_SESSION['seedval'] = $seedval;
$_SESSION['pagecounter'] = 0;

$date_now = date("Y-m-d H:m:s",time());

include('connect-db.php');

$sql_script = "INSERT INTO usershisto(UserId,activity,DateTime) VALUES($userid,1,'".$date_now."')";
$result = mysql_query($sql_script)	or die(mysql_error()); 

header("location:login_success.php"); 
}
else {
   header("location:auth_failed.php");

//header("location:main_login.php");
}

ob_end_flush();
?>


